package com.zretc.service.impl;

import com.zretc.dao.*;
import com.zretc.entity.*;
import com.zretc.service.OrderService;
import com.zretc.service.TrackService;
import com.zretc.util.Util;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author 子玉
 * 订单业务
 */
@Service
public class OrderServiceImpl implements OrderService {

    // 引入dao层
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private TypeMapper typeMapper;

    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private AddressInfoMapper addressInfoMapper;

    @Autowired
    private HouseMapper houseMapper;

    @Autowired
    private TrackService trackService;
    @Autowired
    JedisPool jedisPool;

    @Override
    public boolean addOrder(Map<String, Object> map) {

        // 新建Order对象
        Order order = new Order();

        // 订单号生成
        long time = System.currentTimeMillis(); // 获取时间戳
        String orderId = "EDS" + time;           // "EDS"简单标识
        order.setOrderId(orderId);

        // 默认订单状态为0(待付状态)
        order.setState(0);

        // 获取商品类型名称
        String typeName = (String) map.get("typeName");

        // 获取物品类型对象
        Type type = typeMapper.selectByTypeName(typeName);
        order.setType(type);

        // 获取物品重量
        Double weight = (Double) map.get("weight");
        order.setWeight(weight);

        // 获取备注信息
        String comment = (String) map.get("comment");
        order.setComment(comment);

        // 获取物品类型其他数据
        Double basePrice = type.getBasePrice();              // 基本费用
        Double baseWeight = type.getBaseWeight();            // 基本重量
        Double weightStep = type.getWeightStep();            // 每公斤费用
        Double overWeightLimit = type.getOverWeightLimit();  // 重量限制
        Double overWeightStep = type.getOverWeightStep();    // 超出限制每公斤费用
        Double weightLimit = type.getWeightLimit();          // 最终重量限制
        // 结算总的金额
        // 初始化金额
        Double cost = 0.0;

        // 进行判断
        if (weight <= baseWeight) {
            // 金额等于基本费用
            cost = basePrice;
        } else if (weight > baseWeight && weight <= overWeightLimit) {
            // 金额等于基本费用 + 超出限制1费用
            cost = basePrice + (weight - baseWeight) * weightStep;

        } else if (weight > overWeightLimit && weight <= weightLimit) {
            // 金额等于基本费用 + 超出限制1费用 + 超出限制2费用
            cost = basePrice + (overWeightLimit - baseWeight) * weightStep + (weight - overWeightLimit) * overWeightStep;
        }

        // 设置金额
        order.setCost(cost);

        // 新建AddressInfo对象(收件人)
        AddressInfo addressInfo1 = new AddressInfo();

        // 获取收件人姓名 + 电话 + UUID生成信息地址编号
        String personName1 = (String) map.get("personName1");
        String phone1 = (String) map.get("phone1");
        String uuid1 = UUID.randomUUID().toString().replaceAll("-", "");

        addressInfo1.setAddressInfoId(uuid1);
        addressInfo1.setPersonName(personName1);
        addressInfo1.setPhone(phone1);

        // 新建AddressInfo对象(寄件人)
        AddressInfo addressInfo2 = new AddressInfo();

        // 获取寄件人姓名 + 电话 + UUID生成信息地址编号
        String personName2 = (String) map.get("personName2");
        String phone2 = (String) map.get("phone2");
        String uuid2 = UUID.randomUUID().toString().replaceAll("-", "");

        addressInfo2.setAddressInfoId(uuid2);
        addressInfo2.setPersonName(personName2);
        addressInfo2.setPhone(phone2);

        // 新建Address对象(收件人) + get和set方法
        Address address1 = new Address();

        // 未用UUID生成(测试专用、以后记得删除) UUID.randomUUID().toString().replaceAll("-", "")
        address1.setAddressId("收件人1");
        address1.setAddressName((String) map.get("addressName1"));
        address1.setLat((Double) map.get("lng1"));
        address1.setLng((Double) map.get("let1"));
        address1.setDistrict((String) map.get("district1"));
        address1.setAdCode((String) map.get("adCode1"));
        //address1.setAddress((String) map.get("address1"));
        //address1.setTypeCode((String) map.get("typeCode1"));

        // 新增记录(address + addressInfo)
        addressMapper.insertAddress(address1);
        addressInfo1.setAddress(address1);
        addressInfoMapper.insertAddressInfo(addressInfo1);
        order.setReceiveId(addressInfo1);

        // 新建Address对象(寄件人) + 构造方法
        // 未用UUID生成(测试专用、以后记得删除) UUID.randomUUID().toString().replaceAll("-", "")
        //Address address2 = new Address("寄件人1",
        //        (String) map.get("addressName2"),
        //        (Double) map.get("lng2"),
        //        (Double) map.get("let2"),
        //        (String) map.get("district2"),
        //        (String) map.get("adCode2"),
        //        (String) map.get("address2"),
        //        (String) map.get("typeCode2"));

        // 新增记录(address + addressInfo)
        //addressMapper.insertAddress(address2);
        //addressInfo2.setAddress(address2);
        addressInfoMapper.insertAddressInfo(addressInfo2);
        order.setSendId(addressInfo2);

        // 根据地址名称获取仓库对象
        House house = houseMapper.selectHouseByAddressId(address1.getAddressId());

        order.setEndHouse(house);

        // 新增记录(order订单表)
        int i = orderMapper.insertOrder(order);

        return i == 1 ? true : false;
    }

    /**
     * 添加订单信息
     *
     * @param order@author: bLUeSuMMerDreamer
     * @date: 2020/7/24 21:18
     * @return: java.lang.Boolean
     */
    @Override
    @Transactional
    public Boolean addOrder2(Order order) {
        Boolean insertSendInfo = true;
        Boolean insertReceiveInfo = true;
        if (order.getSendId().getUser() == null) {
            if (addressMapper.insertAddress(order.getSendId().getAddress()) == 1)
                insertSendInfo = addressInfoMapper.insertAddressInfo(order.getSendId()) == 1;
            else {
                insertSendInfo = false;
            }
        }
        if (order.getReceiveId().getUser() == null) {
            if (addressMapper.insertAddress(order.getReceiveId().getAddress()) == 1)
                insertReceiveInfo = addressInfoMapper.insertAddressInfo(order.getReceiveId()) == 1;
            else {
                insertReceiveInfo = false;
            }
        }
        if (insertSendInfo && insertReceiveInfo) {
            return orderMapper.insertOrder(order) == 1;
        } else {
            return false;
        }

    }


    /**
     * 根据参数更新订单
     *
     * @param: setParam
     * @param: whereParam
     * @author: bLUeSuMMerDreamer
     * @date: 2020/7/26 3:18
     * @return: java.lang.Integer
     */
    @Override
    public Integer updateOrderByParam(Map<String, Object> setParam, Map<String, Object> whereParam) {
        return orderMapper.updateOrder(setParam, whereParam);
    }

    /**
     * 根据Id拿到Order
     *
     * @param orderId@author: bLUeSuMMerDreamer
     * @date: 2020/7/28 0:32
     * @return: com.zretc.entity.Order
     */
    @Override
    public Order getOrderById(String orderId) {
        Map<String, Object> params = new HashMap<>();
        params.put("orderId", orderId);
        params.put("unExist", 1);
        params.put("state", 0);
        params.put("orderBy", "timestamp");
        params.put("orderType", "DESC");
        List<Order> orders = orderMapper.findOrderByParams(params);
        if (orders.size() != 0) {
            return orders.get(0);
        } else {
            return null;
        }
    }

    /**
     * 根据参数获取order列表
     *
     * @param params@author: bLUeSuMMerDreamer
     * @date: 2020/7/29 2:50
     * @return: java.util.List<com.zretc.entity.Order>
     */
    @Override
    public List<Order> getOrderByParam(Map<String, Object> params) {
        return orderMapper.findOrderByParams(params);
    }
}
